package com.shali.wechat.order.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
public class ClientWithRestTemplateController {

	@Autowired
	private LoadBalancerClient loadBalancerClient;
	
//	@Autowired
//	private RestTemplate restTemplate;
	
	@GetMapping("getMsg")
	public String getProductMsg() {
		
		//第一种方式 直接用restTemplate调用
//		RestTemplate restTemplate = new RestTemplate();
//		String response = restTemplate.getForObject("http://localhost:8080/msg", String.class);
		
		//第二种方式 利用LoadBalancerClient 获得url，再用restTemplate调用
		RestTemplate restTemplate = new RestTemplate();
		ServiceInstance choose = loadBalancerClient.choose("MICROSERVICE-WECHAT-ORDER-PRODUCT");
		String response = restTemplate.getForObject("http://"+choose.getHost()+":"+choose.getPort()+"/msg", String.class);
		//第三种方式 利用LoadBalanced注解， 在restTemplate中直接使用instance id 调用
//		String response = restTemplate.getForObject("http://MICROSERVICE-WECHAT-ORDER-PRODUCT/msg", String.class);
		log.info("【response】->>{}",response);
		return response;
	}
}
